;; -*- lexical-binding: t -*-

;; Some completion settings.

(defvaralias 'company-candidates 'corfu--candidates)
(defalias 'company-mode 'corfu-mode) ;; should be deleted
(defvaralias 'company-mode 'corfu-mode) ;; should be deleted
(setq company-backends '())
(setq completion-at-point-functions-backup completion-at-point-functions)
(provide 'company)
(require 'corfu)
;; (require 'corfu-doc)
(require 'cape)

(with-eval-after-load 'company-english-helper
  (setq company-english-helper-candidate-max-width 25))

(with-eval-after-load 'corfu
  (setq corfu-cycle t)
  (setq corfu-auto t)
  (setq corfu-quit-no-match t)
  (setq corfu-preview-current nil)
  ;; (setq corfu-echo-documentation nil)
  (setq corfu-auto-prefix 1)
  ;; (define-key corfu-map [tab] #'corfu-next)
  ;; (define-key corfu-map [backtab] #'corfu-previous)
  ;; (define-key corfu-map [escape] #'corfu-quit)
  ;; (when (featurep 'corfu-doc)
  ;;   (add-hook 'corfu-mode-hook #'corfu-doc-mode))
  (ignore-errors
    (require 'kind-icon)
    (when (featurep 'kind-icon)
      (setq kind-icon-default-face 'corfu-default)
      (add-to-list 'corfu-margin-formatters #'kind-icon-margin-formatter)))
  (global-corfu-mode))

;; corfu backend
(add-to-list 'completion-at-point-functions #'cape-file)
(add-to-list 'completion-at-point-functions #'cape-tex)
(add-to-list 'completion-at-point-functions #'cape-dabbrev)
(add-to-list 'completion-at-point-functions #'cape-keyword)

;; (add-hook 'corfu-mode-hook #'corfu-doc-mode)

;; (defun toggle-corfu-english-helper ()
;;   (interactive)
;;   (if (not (featurep 'company-english-helper))
;;       (require 'company-english-helper))
;;   (unless corfu-mode
;;     (corfu-mode t))
;;   (make-variable-buffer-local 'completion-at-point-functions)
;;   (setq completion-at-point-functions
;; 	(list (cape-company-to-capf #'company-english-helper-search)))
;;   (message "English helper has enable."))

(defun set-completion-functions ()
  (setq completion-at-point-functions (cl-concatenate 'list (mapcar #'cape-company-to-capf company-backends) completion-at-point-functions-backup)))

(defun company-grab-symbol ()
  "If point is at the end of a symbol, return it.
    Otherwise, if point is not inside a symbol, return an empty string."
  (if (looking-at "\\_>")
      (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
                                                (point)))
    (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
      "")))

(advice-add 'toggle-company-english-helper :after #'set-completion-functions)

(require 'company-english-helper)
